// pages/index/index.js
const { request } = require('../../API/request.js');
var timer = null;
Page({

  data: {
    deviceList: [],
    choosedDevice: null,//单击的设备
    longPressDevice: null,//长按的设备
    show: false,//弹窗显隐
    alcohol: '--',
    temp: '--',
    humi: '--'
  },

  onLoad() {
    this.getDeviceList();
  },

  //长按出现弹窗
  showDialog(e) {
    this.setData({
      show: true,
      longPressDevice: e.currentTarget.dataset.device
    })
  },

  chooseDevice(e) {
    this.setData({
      choosedDevice: e.currentTarget.dataset.device
    })
    this.getDeviceDetail(e.currentTarget.dataset.device.deviceId)
  },

  //解绑设备
  delete() {
    request('system/device/unBindDevice', 'post', {
      deviceId: this.data.longPressDevice.deviceId
    }).then(() => {
      this.getDeviceList();
    })
  },

  //查询设备列表
  getDeviceList() {
    request('system/device/listDevice', 'get').then((response) => {
      this.setData({
        deviceList: response.rows,
        choosedDevice: response.rows.length > 0 ? response.rows[0] : null
      })
    }).then(() => {
      this.getDeviceDetail(this.data.choosedDevice.deviceId)
    })
  },
  getDeviceDetail(deviceId) {
    console.log('设备ID：', deviceId);
    request(`system/device/getDeviceInfoByDeviceId?deviceId=${deviceId}`, 'get').then((res) => {
      console.log(res);
      try {
        clearTimeout(timer)
      } catch (error) {
        console.log(error);
      }
      this.setData({
        alcohol: JSON.parse(res.data.statusRemark).alcohol,
        temp: JSON.parse(res.data.statusRemark).temp,
        humi: JSON.parse(res.data.statusRemark).humi,
      })

    }).then(() => {
      timer = setTimeout(() => {
        this.getDeviceDetail(deviceId)
      }, 5000)
    }).catch(()=>{
      this.setData({
        alcohol: '--',
        temp: '--',
        humi: '--',
      })
      wx.showToast({
        title: '请求失败',
        icon:'error'
      })
    });

  },
  goSearch() {
    wx.navigateTo({
      url: '/pages/add/index',
    })
  },

  onUnload() {
    try {
      clearTimeout(timer)
    } catch (error) {

    }
  }

})